package com.travelsky.airchina.boarding.web.admin;


import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.travelsky.airchina.boarding.common.ConstType;
import com.travelsky.airchina.boarding.domain.News;
import com.travelsky.airchina.boarding.domain.NewsColumn;
import com.travelsky.airchina.boarding.domain.User;
import com.travelsky.airchina.boarding.dto.NewsSearchCondition;
import com.travelsky.airchina.boarding.dto.NewsUpdateStatus;
import com.travelsky.airchina.boarding.dto.NewsView;
import com.travelsky.airchina.boarding.service.NewsColumnService;
import com.travelsky.airchina.boarding.service.NewsService;
import com.travelsky.airchina.boarding.util.PageUtil;
import com.travelsky.airchina.boarding.web.validator.VideoValidator;

/**
 * 视频转换控制类
 * @author haichenwang
 *
 */
@Controller
@RequestMapping(value="/system/video")
public class VideoController {
	@Autowired
	private NewsColumnService newsColumnService;
	@Autowired
	private NewsService newsService;
	/**
	 * 在新闻列表页面进行查询,分页等操作
	 * @param id 父新闻栏目的主键
	 * @param model
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/list", method=RequestMethod.POST)
	public String list(Model model,@RequestParam int perPageRow,@RequestParam int curPage, HttpServletRequest request) {
		List<Long> roleColumnIdList = (List<Long>)request.getSession().getAttribute(ConstType.ROLE_NEWS_COLUMN_IDS);
		PageUtil pageUtil = new PageUtil();
		pageUtil.setCurPage(curPage);
		pageUtil.setPerPageRow(perPageRow);
		NewsSearchCondition newsSearchCondition = new NewsSearchCondition();
		newsSearchCondition.setColumnIds(roleColumnIdList);//设置用户的授权栏目
		newsSearchCondition.setIsVideo("1");//设置搜索视频条件
		List<NewsView> list = newsService.findNewsPage(pageUtil, newsSearchCondition);
		model.addAttribute("pageUtil",pageUtil);
		model.addAttribute("list",list);
		model.addAttribute("NEWS_STATUS_NO_AUDIT",ConstType.NEWS_STATUS_NO_AUDIT);
		model.addAttribute("NEWS_STATUS_AUDIT_PUBLISH",ConstType.NEWS_STATUS_AUDIT_PUBLISH);
		model.addAttribute("NEWS_STATUS_AUDIT_NOT_PASS",ConstType.NEWS_STATUS_AUDIT_NOT_PASS);
		model.addAttribute("NEWS_STATUS_AUDIT_ARCHIVE",ConstType.NEWS_STATUS_AUDIT_ARCHIVE);
		return "system/news/newsList";
	}
	/**
	 * 角色视频列表首页
	 * @param model
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/manage", method=RequestMethod.GET)
	public String manage(Model model,HttpServletRequest request) {
		List<Long> roleColumnIdList = (List<Long>)request.getSession().getAttribute(ConstType.ROLE_NEWS_COLUMN_IDS);
		PageUtil pageUtil = new PageUtil();
		NewsSearchCondition newsSearchCondition = new NewsSearchCondition();
		newsSearchCondition.setColumnIds(roleColumnIdList);//设置用户的授权栏目
		newsSearchCondition.setIsVideo("1");//设置搜索视频条件
		List<NewsView> videoList = newsService.findNewsPage(pageUtil,newsSearchCondition);
		model.addAttribute("list",videoList);
		model.addAttribute("NEWS_STATUS_NO_AUDIT",ConstType.NEWS_STATUS_NO_AUDIT);
		model.addAttribute("NEWS_STATUS_AUDIT_PUBLISH",ConstType.NEWS_STATUS_AUDIT_PUBLISH);
		model.addAttribute("NEWS_STATUS_AUDIT_NOT_PASS",ConstType.NEWS_STATUS_AUDIT_NOT_PASS);
		model.addAttribute("NEWS_STATUS_AUDIT_ARCHIVE",ConstType.NEWS_STATUS_AUDIT_ARCHIVE);
		setRequestOperationFlag(request);
		return "system/video/videoList";
	}
	/**
	 * 转到创建视频页面
	 * @param model
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(method=RequestMethod.GET)
	public String toCreate(Model model,HttpServletRequest request) {
		List<Long> roleColumnIdList = (List<Long>)request.getSession().getAttribute(ConstType.ROLE_NEWS_COLUMN_IDS);
		List<NewsColumn> newsColumnList = newsColumnService.findAuthorityNewsColumnsByParentId(null,roleColumnIdList);
		model.addAttribute(newsColumnList);
		model.addAttribute(new News());
		return "system/video/createForm";
	}
	/**
	 * 创建视频
	 * @param user
	 * @param result
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(method=RequestMethod.POST)
	public String create(@ModelAttribute("news") News video, BindingResult result,Model model,@RequestParam MultipartFile videoFile,HttpServletRequest request) throws IOException {		
		String newsColumnId = request.getParameter("p_cate_id");
		if(newsColumnId!=null&&!"-1".equals(newsColumnId)){
			NewsColumn newsColumn = new NewsColumn();
			newsColumn.setId(new Long(newsColumnId));
			video.setNewsColumn(newsColumn);
		}
		video.setIsVideo("1");//设置视频标志
		String content = request.getParameter("content");
		video.setContent(content);
		new VideoValidator().validate(video,videoFile,result);
		if(result.hasErrors()){
			List<Long> roleColumnIdList = (List<Long>)request.getSession().getAttribute(ConstType.ROLE_NEWS_COLUMN_IDS);		
			if(video.getNewsColumn()!=null&&video.getNewsColumn().getId()!=null){
				getColumns(model,video.getNewsColumn().getId(),roleColumnIdList);
			}
			model.addAttribute("hasError", true);
			model.addAttribute("content",video.getContent());
			return "system/video/createForm";
		}
		
		if(videoFile!=null && videoFile.getSize()>0){
			String rootDir = request.getSession().getServletContext().getRealPath("/");
			DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
			Date currentTime = new Date();
			String nowDate = dateFormat.format(currentTime);
			long currentTimeL = currentTime.getTime();
			String videoName = currentTimeL + ".flv";
			File flvVideoSavePath = new File(rootDir + ConstType.FLV_VIDEO_PATH + "/" + nowDate);
			if(!flvVideoSavePath.exists()){
				flvVideoSavePath.mkdirs();
			}
			File originalFile = new File(rootDir + ConstType.FLV_VIDEO_PATH + "/" + nowDate + "/" + videoName);
			FileCopyUtils.copy(videoFile.getBytes(),originalFile);
			video.setVideoPath("/" + nowDate + "/" + videoName);
		}
		video.setStatus(ConstType.NEWS_STATUS_NO_AUDIT);
		video.setCreatedTime(new Date());
		User user = (User)request.getSession().getAttribute(ConstType.ADMIN_SESSION_USER);
		video.setUser(user);
		newsService.saveOrUpdateNews(video);
		setSessionOperationFlag(request,"t");
		return "redirect:/system/video/view/" + video.getId();
	}
	
	/**
	 * 根据目录主键获得整个目录显示列表
	 * @param model
	 * @param columnId
	 */
	private void getColumns(Model model,Long columnId,List<Long> roleColumnIdList){
		if(columnId!=null){
			List<NewsColumn> rootNewsColumnTemps = newsColumnService.findNewsColumnsByParentId(null);
			List<NewsColumn> rootNewsColumns = new ArrayList<NewsColumn>();
			if(rootNewsColumnTemps!=null){
				for(NewsColumn temp:rootNewsColumnTemps){
					if(roleColumnIdList.contains(temp.getId())){
						rootNewsColumns.add(temp);
					}
				}
			}
			List<NewsColumn> parentNewsColumns = newsColumnService.findAllParentNewsColumnsByChildId(columnId);
			List<Long> newsColumnIds = new ArrayList<Long>();
			Map<Long,List<NewsColumn>> map = null;
			if(parentNewsColumns!=null && parentNewsColumns.size()>0){
				for(NewsColumn temp:parentNewsColumns){
					newsColumnIds.add(temp.getId());
				}
				map = newsColumnService.findChildrenNewsColumnByParentId(newsColumnIds);
				Long rootNewsColumnId = newsColumnIds.get(0);
				model.addAttribute("rootNewsColumnId",rootNewsColumnId);
			}else{
				model.addAttribute("rootNewsColumnId",columnId);
				map = new HashMap<Long,List<NewsColumn>>();
			}
			model.addAttribute("rootNewsColumns",rootNewsColumns);
			model.addAttribute("newsColumnId",columnId);
			//model.addAttribute("rootNewsColumns",rootNewsColumns);
			model.addAttribute("map",map);
			model.addAttribute("newsColumnIds",newsColumnIds);
		}
	}
	/**
	 * 转到修改视频页面
	 * @param id 视频的主键
	 * @param model
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/update/{id}", method=RequestMethod.GET)
	public String toUpdate(@PathVariable Long id, Model model,HttpServletRequest request) {
		News video = newsService.getNews(id);
		model.addAttribute("news",video);
		model.addAttribute("content",video.getContent());
		
		if(video.getNewsColumn()!=null && video.getNewsColumn().getId()!=null){
			List<Long> roleColumnIdList = (List<Long>)request.getSession().getAttribute(ConstType.ROLE_NEWS_COLUMN_IDS);	
			getColumns(model,video.getNewsColumn().getId(),roleColumnIdList);
		}
		model.addAttribute("NEWS_STATUS_NO_AUDIT",ConstType.NEWS_STATUS_NO_AUDIT);
		model.addAttribute("NEWS_STATUS_AUDIT_PUBLISH",ConstType.NEWS_STATUS_AUDIT_PUBLISH);
		model.addAttribute("NEWS_STATUS_AUDIT_NOT_PASS",ConstType.NEWS_STATUS_AUDIT_NOT_PASS);
		model.addAttribute("NEWS_STATUS_AUDIT_ARCHIVE",ConstType.NEWS_STATUS_AUDIT_ARCHIVE);
		model.addAttribute("FLV_VIDEO_PATH",ConstType.FLV_VIDEO_PATH);
		return "system/video/updateForm";
	}
	/**
	 * 修改视频页面
	 * @param id 视频的主键
	 * @param model
	 * @return
	 * @throws IOException 
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/update", method=RequestMethod.POST)
	public String update(@ModelAttribute("news") News video, BindingResult result,@RequestParam MultipartFile videoFile,Model model,HttpServletRequest request) throws IOException {
		String newsColumnId = request.getParameter("p_cate_id");
		if(newsColumnId!=null&&!"-1".equals(newsColumnId)&&!"".equals(newsColumnId)){
			NewsColumn newsColumn = new NewsColumn();
			newsColumn.setId(new Long(newsColumnId));
			video.setNewsColumn(newsColumn);
		}
		video.setIsVideo("1");//设置视频标志
		String content = request.getParameter("content");
		video.setContent(content);
		new VideoValidator().validate(video,videoFile,result);
		if(result.hasErrors()){
			List<Long> roleColumnIdList = (List<Long>)request.getSession().getAttribute(ConstType.ROLE_NEWS_COLUMN_IDS);
			if(video.getNewsColumn()!=null&&video.getNewsColumn().getId()!=null){
				getColumns(model,video.getNewsColumn().getId(),roleColumnIdList);
			}
			model.addAttribute("content",video.getContent());
			return "system/video/updateForm";
		}
		
		if(videoFile!=null && videoFile.getSize()>0){
			String rootDir = request.getSession().getServletContext().getRealPath("/");
			DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
			Date currentTime = new Date();
			String nowDate = dateFormat.format(currentTime);
			long currentTimeL = currentTime.getTime();
			String videoName = currentTimeL + ".flv";
			File flvVideoSavePath = new File(rootDir + ConstType.FLV_VIDEO_PATH + "/" + nowDate);
			if(!flvVideoSavePath.exists()){
				flvVideoSavePath.mkdirs();
			}
			File originalFile = new File(rootDir + ConstType.FLV_VIDEO_PATH + "/" + nowDate + "/" + videoName);
			FileCopyUtils.copy(videoFile.getBytes(),originalFile);
			video.setVideoPath("/" + nowDate + "/" + videoName);
		}else{
			String originalVideoPath = request.getParameter("originalVideoPath");
			video.setVideoPath(originalVideoPath);
		}
		User user = (User)request.getSession().getAttribute(ConstType.ADMIN_SESSION_USER);
		video.setUser(user);
		newsService.saveOrUpdateNews(video);
		setSessionOperationFlag(request,"t");
		return "redirect:/system/video/view/" + video.getId();
	}
	/**
	 * 查看视频信息
	 * @param id
	 * @param model
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/view/{id}", method=RequestMethod.GET)
	public String getView(@PathVariable Long id, Model model,HttpServletRequest request) {
		News video = newsService.getNews(id);
		model.addAttribute("news",video);
		model.addAttribute("content",video.getContent());
		
		if(video.getNewsColumn()!=null && video.getNewsColumn().getId()!=null){
			List<Long> roleColumnIdList = (List<Long>)request.getSession().getAttribute(ConstType.ROLE_NEWS_COLUMN_IDS);
			getColumns(model,video.getNewsColumn().getId(),roleColumnIdList);
		}
		model.addAttribute("NEWS_STATUS_NO_AUDIT",ConstType.NEWS_STATUS_NO_AUDIT);
		model.addAttribute("NEWS_STATUS_AUDIT_PUBLISH",ConstType.NEWS_STATUS_AUDIT_PUBLISH);
		model.addAttribute("NEWS_STATUS_AUDIT_NOT_PASS",ConstType.NEWS_STATUS_AUDIT_NOT_PASS);
		model.addAttribute("NEWS_STATUS_AUDIT_ARCHIVE",ConstType.NEWS_STATUS_AUDIT_ARCHIVE);
		model.addAttribute("FLV_VIDEO_PATH",ConstType.FLV_VIDEO_PATH);
		setRequestOperationFlag(request);
		return "system/video/view";
	}
	/**
	 * 删除新闻
	 * @return
	 */
	@RequestMapping(value="/delete/{id}", method=RequestMethod.GET)
	public String delete(@PathVariable Long id,HttpServletRequest request) {
		newsService.deleteNews(id);
		/**
		 * 删除视频的同时还需要删除视频文件(待做)
		 */
		setSessionOperationFlag(request,"t");
		return "redirect:/system/video/manage";
	}
	/**
	 * 通过ajax更新新闻的状态
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/updatestatus", method=RequestMethod.GET)
	public @ResponseBody NewsUpdateStatus updateNewsStatus(@RequestParam Long id,@RequestParam String status) {
		NewsUpdateStatus newsUpdateStatus = new NewsUpdateStatus();
		boolean updateFlag = newsService.updateNewsStatus(id, status);
		newsUpdateStatus.setUpdateFlag(updateFlag);
		return newsUpdateStatus;
	}
	/**
	 * 操作后设置操作成功或失败的标志
	 * @param request
	 * @param operationFlag
	 */
	private void setSessionOperationFlag(HttpServletRequest request,String operationFlag){
		request.getSession().setAttribute("operationFlag", operationFlag);
	}
	/**
	 * 从session中取得操作成功或失败的标志,并设置在request
	 * @param request
	 */
	private void setRequestOperationFlag(HttpServletRequest request){
		HttpSession session = request.getSession();
		String operationFlag = (String)session.getAttribute("operationFlag");
		if(operationFlag!=null){
			request.setAttribute("operationFlag", operationFlag);
			session.removeAttribute("operationFlag");
		}
	}
}
